package com.banyechan.lingo_words.entity;


import com.banyechan.lingo_words.exception.BusinessException;
import com.banyechan.lingo_words.exception.BusinessExceptionEnum;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * 全局公共响应对象
 *
 * @param <T>
 *
 */
@Data
@Accessors(chain = true)
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 是否成功：true，成功；false，失败
     */
    private Boolean success;

    /**
     * 成功时返回 ok，失败时返回具体错误消息
     */
    private String message;

    /**
     * <P>业务代码</P>
     * 成功为0,失败时返回具体错误码
     */
    private Integer code;

    /**
     * 成功时具体返回值，失败时为 null
     */
    private T data;

    public static <T> R<T> ok() {
        return ok(null);
    }

    public static <T> R<T> ok(T data) {
        return R(Boolean.TRUE, REnum.OK.getCode(), REnum.OK.getMsg(), data);
    }

    public static <T> R<T> fail(BusinessException ex) {
        return fail(ex.getCode(), ex.getMessage());
    }

    public static <T> R<T> fail(BusinessExceptionEnum exceptionEnum) {
        return fail(exceptionEnum.getCode(), exceptionEnum.getMsg());
    }

    public static <T> R<T> fail(String message) {
        return fail(REnum.FAIL.getCode(), message);
    }

    public static <T> R<T> fail(Integer code, String message) {
        return R(Boolean.FALSE, code, message, null);
    }

    public static <T> R<T> fail(Integer code, String message, T data) {
        return R(Boolean.FALSE, code, message, data);
    }

    private static <T> R<T> R(Boolean success, int code, String message, T data) {
        R<T> R = new R<>();
        R.setSuccess(success);
        R.setCode(code);
        R.setMessage(message);
        R.setData(data);
        return R;
    }

    private R() {
    }
}
